<template>
  <div>数组去重的方法</div>
</template>

<script>
// 方法一
// 1
Array.prototype.unique1 = function () {
  const newArray = [];
  let isRepeat;
  for( let i = 0; i < this.length; i++) {
      isRepeat = false;
      for(let j = 0; j < newArray.length; j++) {
          if(this[i] === newArray[j]) {
              isRepeat = true;
              break;
          }
      }
      if(!isRepeat) {
          newArray.push(this[i]);
      }
  }
  return newArray;
}

var a = [1,2,3,4,5,6,5,4];
console.log(a.unique1()) // (6) [1, 2, 3, 4, 5, 6]

// 2
Array.prototype.unique2 = function () {
  const newArray = [];
  let isRepeat;
  for (let i = 0; i < this.length; i++) {
    isRepeat = false;
    for (let j = i + 1; j < this.length; j++) {
      if (this[i] === this[j]) {
        isRepeat = true;
        break;
      }
    }
    if (!isRepeat) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}

a.unique2() // (6) [1, 2, 3, 6, 5, 4]

// 思路二的写法改进版，实现三：
Array.prototype.unique3 = function () {
  const newArray = [];
  
  for (let i = 0; i < this.length; i++) {
    for (let j = i + 1; j < this.length; j++) {
      if (this[i] === this[j]) {
        j = ++i;
      }
    }
    newArray.push(this[i]);
  }
  return newArray;
}

a.unique3()

// 4 使用filter
Array.prototype.unique4 = function () {
  return this.filter((item, index) => {
    return this.indexOf(item) === index;
  })
}
a.unique4()


// 先排序再去重
Array.prototype.unique5 = function () {
  const newArray = [];
  this.sort();
  for (let i = 0; i < this.length; i++) {
    if (this[i] !== this[i + 1]) {
      newArray.push(this[i]);
    }
  }
  return newArray;
}
a.unique5()

// includes
Array.prototype.unique6 = function () {
  const newArray = [];
  this.forEach(item => {
    if (!newArray.includes(item)) {
      newArray.push(item);
    }
  });
  return newArray;
}

a.unique6()

//  reduce
Array.prototype.unique7 = function () {
  return this.sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length - 1] !== current){
      init.push(current);
    }
    return init;
  }, []);
}

a.unique7()

// Map 
Array.prototype.unique8 = function () {
  const newArray = [];
  const tmp = new Map();
  for(let i = 0; i < this.length; i++){
        if(!tmp.get(this[i])){
            tmp.set(this[i], 1);
            newArray.push(this[i]);
        }
    }
    return newArray;
}

a.unique8()

// Set
Array.prototype.unique9 = function () {
  return [...new Set(this)];
}
a.unique9()



export default {

}
</script>

<style scoped>

</style>